import {
  Component,
  ChangeDetectionStrategy,
  OnDestroy,
  ViewChild,
  ElementRef,
  ChangeDetectorRef,
  HostListener,
  Output,
  EventEmitter,
  Input,
} from '@angular/core';
import { Subject } from 'rxjs';
import { _HttpClient } from '@delon/theme';
import { MSTopbarService } from '@brand';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

/**
 * 产品搜索框
 */
@Component({
  selector: 'app-product-search',
  templateUrl: './product-search.component.html',
  styleUrls: ['./product-search.component.less'],
  host: {
    '[class.alain-ms__topbar-item]': 'true',
    '[class.mr-md]': 'true',
  },
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductSearchComponent implements OnDestroy {
  @ViewChild('ipt', { static: true })
  private ipt: ElementRef<any>;

  @Input()
  set str(val) {
    this.q = val;
  }

  show = false;
  q: string;
  search$ = new Subject<string>();
  @Output()
  search = new EventEmitter();

  constructor(http: _HttpClient, private cdr: ChangeDetectorRef) {
    this.search$
      .pipe(
        debounceTime(300),
        distinctUntilChanged(),
      )
      .subscribe((res: any) => {
        this.search.emit(res);
        this.cdr.detectChanges();
      });
  }

  @HostListener('click')
  _click() {
    this.ipt.nativeElement.focus();
    this.show = true;
  }

  emit() {
    this.search.emit(this.q);
  }

  ngOnDestroy(): void {
    this.search$.unsubscribe();
  }
}
